<?php
/**
 * Copyright (c) 2012, xxworkshop Inc.
 * All rights reserved.
 *
 * Created by BrocheXu on 2014.11.6
 */
class AccessTokenManager {
	const AccessTokenUrl = 'https://api.weixin.qq.com/cgi-bin/token';
	
	private $appid;
	private $appsecret;
	private $tmpfilename;
	private $accesstoken;
	private $validtimestamp;

	public function __construct($appid, $appsecret) {
		$this->appid = $appid;
		$this->appsecret = $appsecret;
		$this->tmpfilename = dirname(__file__).'/accesstoken.cache';
		if (file_exists($this->tmpfilename)) {
			$fs = fopen($this->tmpfilename, 'r');
			$sdata = fread($fs, filesize($this->tmpfilename));
			$data = json_decode($sdata, true);
			$this->accesstoken = $data['accesstoken'];
			$this->validtimestamp = $data['validtimestamp'];
		}
	}
	
	private function refreshAccessToken() {
		if (empty($this->accesstoken) || $this->validtimestamp < time()) {
			$url = self::AccessTokenUrl.'?grant_type=client_credential&appid='.$this->appid.'&secret='.$this->appsecret;
			$data = file_get_contents($url);
			$jdata = json_decode($data, true);
			if (empty($jdata['access_token'])) {
				throw new Exception('can not get access token. errcode: '.$jdata['errcode'].'    errmsg: '.$jdata['errmsg']);
			}
			$this->accesstoken = $jdata['access_token'];
			$this->validtimestamp = time() + $jdata['expires_in'] - 200;
			$tdata['accesstoken'] = $this->accesstoken;
			$tdata['validtimestamp'] = $this->validtimestamp;
			$fs = fopen($this->tmpfilename, 'w');
			fwrite($fs, json_encode($tdata));
			fclose($fs);
		}
	}
	
	public function getToken() {
		$this->refreshAccessToken();
		return $this->accesstoken;
	}
}

?>